<?php
/**
 * Created by PhpStorm.
 * @author LiShaoWei
 * @param Date : 2016/4/11
 * @param Time : 14:26
 * @since 1.0
 */
namespace app\controllers;
use app\models\BookArticle;
use app\models\Corp;
use app\models\CorpLog;
use app\models\User;
use Yii;
use yii\web\Controller;
use yii\web\ForbiddenHttpException;
use yii\web\HttpException;
use yii\web\Response;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;

class GoodController extends Controller
{
    public function actionIndex($s,$k='北京')
    {
        for($i=1;$i<3;$i++){
            $url='http://sou.zhaopin.com/jobs/searchresult.ashx?jl='.urldecode($k).'&kw='.$s.'&sm=0&p='.$i;
//            echo $url;
//            return file_get_contents($url);
            $this->get($url);

        }
        echo '抓取完成';
    }
    public function Test($title,$content)
    {

//        $mail = \Yii::$app->mailer->compose()
//            ->setFrom(['weisendo@163.com' => '草榴无码社区'])
//            ->setTo('1227008171@qq.com')
//            ->setSubject($title)
//            //->setTextBody('Yii中文网教程真好 www.yii-china.com')   //发布纯文字文本
//            ->setHtmlBody($content.'<br/>http://www.bookbt.net 最好的招聘网站')    //发布可以带html标签的文本
//            ->send();
        $mail = \Yii::$app->mailer->compose()
            ->setFrom(['weisendo@163.com' => '草榴无码社区'])
            ->setTo('1227008171@qq.com')
            ->setSubject($title)
            //->setTextBody('Yii中文网教程真好 www.yii-china.com')   //发布纯文字文本
            ->setHtmlBody($content)    //发布可以带html标签的文本
            ->send();
        if($mail)
            echo 'success'.date('Y-m-d H:i:s');
        else
            echo 'fail';
        sleep(15);
    }
    /**
     * 智联招聘采集
     * @author  LiShaoWei
     * @access  public
     * @since   1.0
     * @throws \yii\db\Exception
     */
    public function get($url)
    {
        $str=$this->vget($url);
       //return $str;
        $strZheng ='/<table cellpadding.*?<\/table>/si';
        preg_match_all ( $strZheng , $str , $array );//匹配出地址和内容
        $CORP= new CorpLog();
        $i=0;
        foreach($array[0] as $as=>$av){
            $titleurl=$url=$this->strSubstr1('http:','htm',$av);
            $titleurl=$url=$this->strSubstr1('http:','htm',$titleurl);
            $title=$this->strSubstr('target="_blank">','</a></td>',$av);

                $CORP::find()->createCommand()->insert('corp_log',[
                    'title'=>$title,
                    'url'=>$titleurl,
                    'create_time'=>time()
                ])->execute();
                $i++;
        }
        $CORP= new CorpLog();
        $model=$CORP::find()->where(['is_state'=>0])->all();
        $i=1;
        foreach($model as $k=>$v){
            $this->Cai($v['url'],$v['title']);
            $CORP::find()->createCommand()->update('corp_log',['is_state'=>1],['id'=>$v['id']])->execute();
            $i++;
        }
//        echo $i;
//        echo '采集'.$i;
    }
    public function actionZc()
    {
        $CORP= new CorpLog();
        $model=$CORP::find()->where(['is_state'=>0])->all();
        $i=1;
        foreach($model as $k=>$v){
            $this->Cai($v['url'],$v['title']);
            $CORP::find()->createCommand()->update('corp_log',['is_state'=>1],['id'=>$v['id']])->execute();
            $i++;
        }
        echo $i;
    }

    /**
     * 智联招聘详细采集
     * @author  LiShaoWei
     * @access  public
     * @param $url
     * @since   1.0
     * @throws \yii\db\Exception
     */
    public function Cai($url,$name){
//$url,$name
        $corpModel= new Corp();
        //$url='http://jobs.zhaopin.com/279941231250111.htm';
        $str=$this->vget($url);

        $array['uid']=$this->generateuuid();
        $array['url']=$url;
        $array['title']=$this->strSubstr('<h1>','</h1>',$str);
        $array['name']=$name;
        $array['money']=$this->strSubstr('</span><strong>','</strong>',$str);
        $array['corp_time']=strtotime($this->strSubstr('id="span4freshdate">','</span>',$str));
        $array['education']=$this->strSubstr('最低学历：</span><strong>','</strong>',$str);
        $array['job_description']=$this->strSubstr('<!-- SWSStringCutStart -->','<!-- SWSStringCutEnd -->',$str);
        $array['experience']=$this->strSubstr('工作经验：</span><strong>','</strong>',$str);
        $array['type']=$this->strSubstr('工作地点：</span><strong>','</strong>',$str);
        $array['type']=$this->strSubstr('>','<', $array['type']);
        $array['recruit_number']=$this->strSubstr('招聘人数：</span><strong>','</strong>',$str);
        $array['address']=trim(strtr($this->strSubstr('工作地址：</b>','</h2>',$str),['<h2>'=>'']));
        $pattern1="/<a href=\"javascript:fnOpenMiniMap.*?<\/a>/si";
        $array['address']= preg_replace($pattern1,"",$array['address']);
        $array['create_time']=time();
        IF(!$corpModel::find()->where(['url'=>$array['url']])->exists()){

            $corpModel::find()->createCommand()->insert('corp',$array)->execute();
        }
        $this->Test($array['type'].'_'.$array['title'].'-'.$array['name'],$array['recruit_number'].'<br/>'
            .$array['experience'].'<br>'
            .$array['address'].'<br>'
            .$array['type']
        );
    }
    public function generateuuid()
    {
        // $this->Cai(substr($array1[0],0,-1),$id);
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = '';
        $hyphen = chr(45);
        $uuid = substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12);
        return $uuid;
    }
    public function strSubstr1($beginStr, $endStr, $contStr) {
        $beginStrNo = strpos($contStr, $beginStr);
        $endStrNo = strpos($contStr, $endStr, $beginStrNo);

        $length = $endStrNo - $beginStrNo+strlen($endStr) ;
        $cont = substr($contStr, $beginStrNo , $length);

        return trim($cont);
    }
    public function strSubstr($beginStr, $endStr, $contStr) {
        $beginStrNo = strpos($contStr, $beginStr);
        $endStrNo = strpos($contStr, $endStr, $beginStrNo);

        $length = $endStrNo - $beginStrNo - strlen($beginStr);
        $cont = substr($contStr, $beginStrNo + strlen($beginStr), $length);

        return trim($cont);
    }
    function vget ( $url , $ucookie='' )
    { // 模拟登录获取Cookie函数

        $curl = curl_init (); // 启动一个CURL会话
        curl_setopt ( $curl , CURLOPT_URL , $url ); // 要访问的地址
        curl_setopt ( $curl , CURLOPT_SSL_VERIFYPEER , 0 ); // 对认证证书来源的检查
        curl_setopt ( $curl , CURLOPT_SSL_VERIFYHOST , 2 ); // 从证书中检查SSL加密算法是否存在
        //curl_setopt ( $curl , CURLOPT_USERAGENT , $_SERVER['HTTP_USER_AGENT'] ); // 模拟用户使用的浏览器
        curl_setopt ( $curl , CURLOPT_FOLLOWLOCATION , 1 ); // 使用自动跳转
        curl_setopt ( $curl , CURLOPT_AUTOREFERER , 1 ); // 自动设置Referer
       // curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt ( $curl , CURLOPT_COOKIEJAR , $ucookie ); // 存放Cookie信息的文件名称
        curl_setopt ( $curl , CURLOPT_COOKIEFILE , $ucookie ); // 读取上面所储存的Cookie信息
        curl_setopt ( $curl , CURLOPT_TIMEOUT , 30 ); // 设置超时限制防止死循环
        curl_setopt ( $curl , CURLOPT_HEADER , 0 ); // 显示返回的Header区域内容
        curl_setopt ( $curl , CURLOPT_RETURNTRANSFER , 1 ); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec ( $curl ); // 执行操作
        if (curl_errno ( $curl )) {
            echo 'Errno' . curl_error ( $curl );
        }
        curl_close ( $curl ); // 关闭CURL会话
        return $tmpInfo; // 返回数据
    }


}